import { InjectionToken, container, singleton, Disposable, scoped, Lifecycle } from "tsyringe";
import { IListener } from "../core/listener";
import { ISender } from "../core/sender";
import * as tokens from '../tokens'
import type { Thread } from 'threads'
import { Record } from "../core/Record";
import { LogCollection } from "../core/LogCollection";

@scoped(Lifecycle.ContainerScoped)
export class RemoteScript implements IListener<tokens.IRemoveScript>, Disposable {
    type: InjectionToken<tokens.IRemoveScript> = tokens.REMOTE_SCRIPT;
    task: Thread;
    on(payload: tokens.IRemoveScript, manager: ISender): void {
        try {
            if (this.task && this.task.isAlive()) {
                this.task.interrupt();
            }
            const record = new Record(new LogCollection())
            record.setDisplayLevel(0)
            this.task = threads.start(() => {
                try {
                    engines.execScript(payload.name, payload.code)
                } catch (e) {
                    toast(e.message)
                }
            });
        } catch (e) {
            toast(e.message)
        }
    }

    dispose(): void | Promise<void> {
        if (this.task && this.task.isAlive()) {
            this.task.interrupt();
        }
    }
}